package com.shen.shenproject.retrofit

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.lifecycleScope
import com.shen.shenproject.R
import com.shen.shenproject.coroutine.retrofit.Repo
import com.shen.shenproject.coroutine.retrofit.RetrofitApi
import io.reactivex.SingleObserver
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_coroutine.*
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
import java.lang.Runnable
import java.util.concurrent.Executor
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * Retrofit
 */
class RetrofitActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coroutine)
    }


    /**
     * Retrofit + OkHttp
     */
    private fun retrofitDemo(){
        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()

        val api = retrofit.create(ShenRetrofitApi::class.java)

        api.listRepos("rengwuxian")
            .enqueue(object : Callback<List<Repo>?>{
                override fun onResponse(call: Call<List<Repo>?>, response: Response<List<Repo>?>) {
                    tv_name.text = response.body()?.get(0)?.name
                }
                override fun onFailure(call: Call<List<Repo>?>, t: Throwable) {

                }
            })

        api.listReposRx("rengwuxian")
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : SingleObserver<List<Repo>>{

                override fun onSubscribe(d: Disposable) {

                }

                override fun onError(e: Throwable) {

                }

                override fun onSuccess(t: List<Repo>) {

                }
            })
    }

//    internal class MainThreadExecutor : Executor {
//        private val handler = Handler(Looper.getMainLooper())
//
//        override fun execute(r: Runnable) {
//            handler.post(r)
//        }
//    }
}
